<!--SMT站位表 导入-->
<template>
  <el-dialog
    width="80%"
    top="5vh"
    title="导入"
    custom-class="smtStandDialog"
    append-to-body
    v-if="showImportDialog"
    :modal-append-to-body="true"
    :close-on-click-modal="false"
    :visible.sync="showImportDialog"
    @close="handleImportReset"
  >
    <avue-form
      ref="importRef"
      v-model="importDialog.form"
      :option="importDialog.option"
      @submit="handleImportSubmit"
      :upload-before="uploadBefore"
      @reset-change="handleImportReset"
    >
      <template slot="excelFile">
        <el-upload
          ref="excelFile"
          class="importConfigDialog"
          drag
          action="#"
          accept=".xlsx,.xls"
          :multiple="true"
          :auto-upload="false"
          :before-remove="handleBeforeRemove"
          :on-change="uploadBefore"
        >
          <!--          limit="1"-->
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">
            <div>请上传 .xlsx,.xls标准格式文件</div>
          </div>
        </el-upload>
      </template>
      <template slot="excelTemplate">
        <el-button :loading="loading" type="primary" class="el-icon-download el-icon--right" @click="handleTemplate('failureCodeExcelBox')">模板下载</el-button>
      </template>
    </avue-form>

    <span slot="footer" class="dialog-footer">
      <el-button size="small" type="primary" icon="el-icon-check" v-preventReClick @click="handleSubmit">保存</el-button>
      <el-button size="small" icon="el-icon-delete" @click="handleReset">取消</el-button>
    </span>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
  </el-dialog>
</template>

<script>
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import { getList, getDetail } from '@/api/product/smttable';
import { mapGetters } from 'vuex';
import { exprot } from '@/api/repair/failureconfig';
import request from '@/router/axios';
import { checkImportData, importData } from '@/api/product/smtStandTable';
import { getToken } from '@/util/auth';
export default {
  name: 'smtImport',
  components: {
    GlobalModalTemplate
  },
  props: {
    showImportDialog: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    urls: {
      type: Object,
      default: () => {}
    }
  },
  watch: {
    showImportDialog: {
      handler(val) {
        this.setImportInfo();
      },
      immediate: true
    }
  },
  data() {
    return {
      importDialog: {
        form: {
          file: []
        },
        loading: null,
        option: {
          searchShow: true,
          searchMenuSpan: 6,
          menuPosition: 'right',
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '附件上传',
              prop: 'excelFile',
              span: 24,
              drag: true,
              type: 'upload',
              loadText: '附件上传中，请稍等',
              propsHttp: {
                res: 'data'
              },
              data: {},
              headers: {
                'Blade-Auth': getToken()
              },
              accept: '.xlsx,.xls',
              tip: '请上传.xls,.xlsx标准格式文件',
              action: '#'
              // action: '/api/blade-resource/oss/endpoint/put-file-attach'
            },
            {
              label: '模板下载',
              prop: 'excelTemplate',
              formslot: true,
              span: 24
            }
          ]
        }
      },
      checkUrl: '',
      importUrl: '',
      // form: {},
      query: {},
      cloneForm: {},
      loading: false,
      selectionList: [],
      data: [],
      visibile: false,
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime() //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.smttable_add, false),
        viewBtn: this.vaildData(this.permission.smttable_view, false),
        delBtn: this.vaildData(this.permission.smttable_delete, false),
        editBtn: this.vaildData(this.permission.smttable_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    replaceMateriaReadOnly() {
      if (this.replaceMateriaDialog.title == '编辑') {
        return false;
      } else {
        return true;
      }
    }
  },
  methods: {
    handleImport() {
      this.showImportDialog = true;
    },
    setImportInfo() {
      const column = [
        {
          label: '附件上传',
          prop: 'excelFile',
          span: 24,
          drag: true,
          type: 'upload',
          loadText: '附件上传中，请稍等',
          propsHttp: {
            res: 'data'
          },
          data: {},
          headers: {
            'Blade-Auth': getToken()
          },
          accept: '.xlsx,.xls',
          tip: '请上传.xls,.xlsx标准格式文件',
          action: '#'
        }
      ];
      this.$set(this.importDialog.option, 'group', null);
      this.$set(this.importDialog.option, 'column', column);
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
          this.cloneForm = this._cloneDeep(res.data.data);
        });
      }
      if (['add', 'edit'].includes(type)) {
      }
      done();
    },
    async handleTemplate() {
      try {
        this.loading = true;
        const data = {
          originalName: 'SMT站位表模板.xlsx',
          attachType: 'EXCEL'
        };
        const res = await exprot({ data });
        const blob = new Blob([res.data]);
        const fileName = 'SMT站位表模板.xlsx';
        const link = document.createElement('a');
        link.download = fileName;
        link.style.display = 'none';
        link.href = URL.createObjectURL(blob);
        document.body.append(link);
        link.click();
        URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
      } catch (e) {
        console.warn(e);
      } finally {
        this.loading = false;
      }
    },
    openUserCommonModal(params) {
      let { type } = params;
      this.visibile = true;

      switch (type) {
        case 'productCode':
          this.tableOption = {
            modalTitle: '选择产品信息（双击进行选择）',
            // rowSelectionType: 'single',
            rowSelectionType: this.multiple ? 'multiple' : 'single',
            menu: false,
            editBtn: false,
            menuWidth: 100,
            searchLabelWidth: 90
          };
          this.tableOption.url = '/api/mes-admin/part-master/page';
          this.tableOption.isPage = true;
          this.tableOption.query = { semifinished: true };
          this.tableOption.templateName = 'NOWORKPARTMASTER';
          this.modalName = 'partmasterModal';
          break;
        case 'machineBrand':
          this.tableOption = {
            modalTitle: '选择设备信息（双击进行选择）',
            rowSelectionType: 'single',
            menu: false,
            editBtn: false,
            menuWidth: 100,
            searchLabelWidth: 90
          };
          this.tableOption.url = '/api/mes-product/ems-equipment/page';
          this.tableOption.isPage = true;
          this.tableOption.query = { equipmentType: 'MACHINE' };
          this.tableOption.templateName = 'EQUIPMENT';
          this.modalName = 'machineBrandModal';
          break;
        default:
          break;
      }
    },
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'partmasterModal':
          if (this.multiple) {
            this.importDialog.form.partNos = rowData.map((r) => r.partNo).join(',');
            this.importDialog.form.partNames = rowData.map((r) => r.name).join(',');
          } else {
            this.importDialog.form.partNos = this._get(rowData, 'partNo', '');
            this.importDialog.form.partNames = this._get(rowData, 'name', '');
          }
          break;
        case 'machineBrandModal':
          this.importDialog.form.machineBrand = this._get(rowData, 'brand', '');
          break;

        default:
          break;
      }
    },
    // 导入保存
    handleSubmit() {
      this.$refs.importRef.submit();
    },
    // 导入取消
    handleReset() {
      this.$refs.importRef.resetForm();
    },
    async handleImportSubmit(form, done) {
      console.log(form, 'form');
      const checkRes = await this.checkImport(form);
      // true :没有同名 false:有同名
      console.log(checkRes, 'checkRes');
      if (checkRes && !checkRes.data) {
        let msg = '是否覆盖原数据?';
        this.$confirm(`${msg}`, {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        })
          .then(async () => {
            await this.importData(form, this.urls.import);
          })
          .catch(() => {});
      } else if (checkRes && checkRes.data) {
        await this.importData(form, this.urls.import);
      }
      done();
    },
    async checkImport(form) {
      if (!form.file || !form.file.length) {
        this.$message.warning('请先上传文件后再操作！');
        return false;
      }
      try {
        let formData = new FormData();
        form.file.forEach((item) => {
          formData.append('file', item);
        });
        console.log(form, formData, 'form');
        const res = await checkImportData(formData, this.urls.check);
        return res.data;
      } catch (e) {
        console.warn(e);
      }
    },
    async importData(form) {
      try {
        if (!form.file || form.file.length === 0) {
          this.$message.warning('请先上传文件后再操作！');
          return;
        }
        let fileParams = new FormData();
        this.importDialog.loading = this.$loading({
          target: '.smtStandDialog'
        });
        Object.keys(form).forEach((item) => {
          if (form[item]) {
            if (item === 'file') {
              form.file.forEach((el) => {
                fileParams.append('file', el);
              });
            } else {
              fileParams.append(item, form[item]);
            }
          }
        });
        console.log(fileParams, 'fileParams');
        const res = await importData(fileParams, this.urls.import);
        this.$message.success('导入成功');
        this.$emit('closeImportDialog');
        this.showImportDialog = false;
        this.$refs.importRef.resetFields();
      } catch (e) {
        console.warn(e);
      } finally {
        this.importDialog.loading.close();
        // this.importDialog.form.file = {};
        this.importDialog.form.file = [];
        this.$refs.excelFile.clearFiles();
      }
    },
    uploadBefore(file) {
      let nameArray = file.name.split('.');
      if (nameArray[nameArray.length - 1] === 'xlsx' || nameArray[nameArray.length - 1] === 'xls') {
        // file保存选择的文件
        this.importDialog.form.file.push(file.raw);
      } else {
        this.$message({
          message: `${file.name}文件格式错误,请确认文件内容并重新上传`,
          type: 'warning',
          duration: 2000
        });
      }
    },
    async handleBeforeRemove(file, fileList) {
      let res = await this.$confirm(`确定移除 ${file.name}？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
      if (res) {
        this.importDialog.form.file = this.importDialog.form.file.filter((item) => item.uid !== file.uid);
        this.$message({
          type: 'success',
          message: '移除成功!'
        });
      }
    },
    handleImportReset() {
      this.showImportDialog = false;
      this.$refs.importRef.resetForm();
      this.$emit('closeImportDialog');
      this.importDialog.form.file = [];
    },
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .smtStandDialog {
  .el-dialog__body {
    padding: 0 20px;
  }
  .avue-form__menu--right {
    display: none;
  }
  .detailTitle {
    font-size: 16px;
    font-weight: bold;
    height: 50px;
    line-height: 50px;
    color: rgba(0, 0, 0, 0.85);
    border-bottom: 1px solid #eee;
  }
  .detailArea {
    .avue-crud__menu {
      display: none;
    }
  }
}
::v-deep .replaceMateriaDialog {
  .row {
    display: flex;
    .deleteIcon {
      margin-left: 10px;
    }
  }
  .addIcon {
    display: flex;
    justify-content: center;
  }
  .avue-crud__menu {
    display: none;
  }
}
</style>
